<?php
namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\common\model\CouponUserTemp;
use app\common\model\User;
use app\common\event\CouponUser as CouponUserEvent;
 
class SendCoupon extends Command
{
	
    protected function configure(){
        $this->setName('SendCoupon')->setDescription('检测需要定时发送的优惠券');
    }
 
    protected function execute(Input $input, Output $output){
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/
        $this->change_income($output);
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }
	
    private function change_income($output){
    	
	 	$coupons = CouponUserTemp::getExpireCoupon();
		
		// 可发放数量为0时，不执行发放动作
		if(count($coupons) < 1){
			$output->writeln('fail--0');
			return fasle;
		}
		
		//获取所有优惠券id，去重
		$couponIds = [];
    	foreach ($coupons as $key => $item) {
    	 	$couponIds[] = $item['coupon_id']; 
    	}
		$couponIds = array_unique($couponIds);  
		 
		//格式化数据
		$data = [];
		foreach ($couponIds as $key => $id) {
			$arr = ["coupon_id"=>$id,"uids"=>[]];
    		foreach ($coupons as $k => $item) {
    			if($item['coupon_id'] == $id){
    				$arr['coupon_name'] = $item['coupon_name'];
    				$arr['uids'][] = $item['uid']; 
    			}
    		}
			$data[] = $arr;
    	}
		
		//发送微信通知
		foreach ($data as $k => $item) {
    		$openids = User::where('id','in',$item['uids'])
    			->where('openid','<>','')
    			->Distinct(true)
    			->column('openid');
			CouponUserEvent::sendTemplateMessage($item['coupon_name'],$openids);	
    	}
		
		//发放优惠券
		Db::query('call xw_extract_coupon_user()');
		
		//添加日志
		Db::name('system_log')->insert([
			'url' =>'定时任务-检测需要定时发送的优惠券', 
			'result'=>'成功：本次共定时发送'.count($coupons).'张优惠券！'
		]);
		
		//控制台通知
		$output->writeln('success--'.count($coupons));
    }
	
}